<!--  -->
<template>
  <div class="loginDialog">
    <el-dialog v-model="loginDialogVisible" width="20%">
      <template #header="{ close, titleId, titleClass }">
        <span style="font-size: 18px">登录</span>
      </template>
      <el-form ref="form" :model="form">
        <el-form-item>
          <el-input v-model="form.username" placeholder="请输入用户名" clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" clearable show-password
            @keyup.enter.native="login">
            <template #prefix>
              <el-icon class="el-input__icon">
                <Lock />
              </el-icon>
            </template>
          </el-input>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login" @click="login" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button link @click="ForgotPassword">忘记密码</el-button>
        </el-form-item>
      </el-form>
      <div>

      </div>
      <el-dialog width="30%" title="忘记密码" v-model="innerVisible" :close-on-click-modal="false"
        @close="innerVisibleCloseDialog">
        <el-steps :active="active" finish-status="success">
          <el-step title="用户名"></el-step>
          <el-step title="验证方式"></el-step>
          <el-step title="重置密码"></el-step>
          <el-step title="验证完成"></el-step>
        </el-steps>
        <el-form label-position="top" label-width="80px" :model="formLabelAlign" class="formLabelAlign"
          :rules="dialogRules" ref="formLabelAlign">
          <el-form-item label="请输入用户名" v-show="active === 0">
            <el-input placeholder="请输入用户名" v-model="formLabelAlign.loginName" clearable>
            </el-input>
          </el-form-item>
          <el-form-item :label="`密保问题1？${formLabelAlign.problem1}`" v-show="active === 1 && checkingWay">
            <el-input placeholder="请输入问题的答案" v-model="formLabelAlign.answer1" clearable>
            </el-input>
          </el-form-item>
          <el-form-item :label="`密保问题2？${formLabelAlign.problem2}`" v-show="active === 1 && checkingWay">
            <el-input placeholder="请输入问题的答案" v-model="formLabelAlign.answer2" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="请联系商家获取秘钥" v-show="active === 1 && !checkingWay">
            <el-input placeholder="请输入秘钥" v-model="formLabelAlign.input" clearable> </el-input>
          </el-form-item>
          <el-form-item label="验证成功，请输入新密码" v-show="active === 2" prop="newLoginPwd">
            <el-input placeholder="请输入新密码" v-model="formLabelAlign.newLoginPwd" show-password clearable
              autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item label="请再次输入新密码" v-show="active === 2">
            <el-input placeholder="再次输入密码'" v-model="formLabelAlign.newLoginPwdAgin" show-password clearable
              autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item v-show="active === 3">
            <el-result icon="success" title="重置成功" :subTitle="`重置成功，${secondsRemaining}秒内将返回登录`">
              <template slot="extra">
                <el-button type="primary" size="medium" @click="innerVisible = false">返回</el-button>
              </template>
            </el-result>
          </el-form-item>
          <div :class="active !== 3 ? 'checking' : ''">


            <el-button type="primary" v-show="active == 1 || active == 2" @click="goBack" class="checkButton">
              上一步</el-button>
            <el-button type="primary" @click="checking" v-show="active !== 3" class="checkingButton">
              {{ toggleButton }}</el-button>
          </div>
        </el-form>


      </el-dialog>
    </el-dialog>
  </div>

</template>

<script>
import rule from '@/utils/rule'
import { sysLogin, settinglist } from '@/api/request'
import { getUserPermissionByToken } from '@/api/sys/power'
import { getProblemList, verification, resetPasswordByProblem } from '@/api/request.js'
import { ElMessage } from 'element-plus';
export default {
  name: 'loginDialog',
  props: {},
  components: {},
  data() {
    return {
      active: 0,
      loginDialogVisible: false,
      innerVisible: false,
      checkingWay: true, //true  为密保验证，false 为秘钥验证
      form: {
        username: '',
        password: '',
      },
      dialogRules: {
        newLoginPwd: [{ required: true, validator: rule.checkPassword, trigger: 'blur' }],
      },
      formLabelAlign: {
        newLoginPwd: '',
        newLoginPwdAgin: '',
      },
      secondsRemaining: 0,
      timerId: null,
      list: [], //密保问题
    }
  },
  computed: {
    toggleButton() {
      if (this.active === 0) {
        return '下一步'
      } else if (this.active === 1) {
        return '验证'
      }
      if (this.active === 2) {
        return '重置'
      } else {
        return ''
      }
    },
  },
  watch: {
    active(newVal) {
      if (newVal === 3) {
        this.startCountdown()
      } else {
        clearInterval(this.timerId)
      }
    },
  },
  methods: {
    getPowerMenu() {
      getUserPermissionByToken().then((res) => {
        if (res.status == 200) {
          // 获取权限菜单的列表
          const arr = res.data.data.menu
          this.$store.commit('getAllMenu', arr)
        }
      })
    },
    startCountdown() {
      this.secondsRemaining = 5 // 设置倒计时总秒数
      this.timerId = setInterval(() => {
        this.secondsRemaining--
        if (this.secondsRemaining <= 0) {
          clearInterval(this.timerId)
          this.secondsRemaining = 0
          this.innerVisible = false
        }
      }, 1000)
    },
    // 获取密保问题
    async getList() {
      try {
        const response = await getProblemList(this.formLabelAlign.loginName)

        if (response.data.code === 200) {
          const data = response.data.data
          this.list = data
          if (data.length === 2) {
            this.formLabelAlign.problem1 = data[0]
            this.formLabelAlign.problem2 = data[1]
            return true // 成功获取两个问题
          } else {
            return false // 数据长度不符合要求
          }
        } else {
          return false // API 返回错误
        }
      } catch (error) {
        return false // 处理网络请求错误
      }
    },
    // 下一步的逻辑
    checking() {
      if (this.active === 0) {
        if (this.formLabelAlign.loginName) {
          this.getList()
            .then((result) => {
              if (result) {
                this.active = 1
              } else {
                ElMessage({
                  message: '用户名不存在',
                  type: 'error',
                });
              }
            })
            .catch((error) => {
              ElMessage({
                message: '获取问题列表失败',
                type: 'error',
              });

            })
        } else {
          ElMessage({
            message: '请输入用户名',
            type: 'error',
          });

        }
      } else if (this.active === 1) {
        this.checkingProblem().then((restult) => {
          if (restult) {
            this.active = 2
          }
        })
      } else if (this.active === 2) {
        this.$refs['formLabelAlign'].validate((valid) => {
          if (valid) {
            this.resetPassword()
          }
        })
      }
    },
    // 验证问题
    async checkingProblem() {
      const parm = {
        list: [
          {
            answer: this.formLabelAlign.answer1,
            problem: this.formLabelAlign.problem1,
          },
          {
            answer: this.formLabelAlign.answer2,
            problem: this.formLabelAlign.problem2,
          },
        ],
        loginName: this.formLabelAlign.loginName,
      }

      try {
        const response = await verification(parm)
        if (response.data.code === 200) {
          const data = response.data.data
          this.list = data
          return true // 成功获取两个问题
        } else {
          ElMessage({
            message: response.data.message,
            type: 'error',
          });


          return false // API 返回错误
        }
      } catch (error) {
        return false // 处理网络请求错误
      }
    },
    // 重置密码
    async resetPassword() {
      // 判断两处次输入密码是否一致
      if (this.formLabelAlign.newLoginPwd !== this.formLabelAlign.newLoginPwdAgin) {
        ElMessage({
          message: '两次输入密码不一致',
          type: 'error',
        });
      } else {
        const params = {
          loginName: this.formLabelAlign.loginName,
          newLoginPwd: this.formLabelAlign.newLoginPwdAgin,
        }
        resetPasswordByProblem(params).then((res) => {
          if (res.data.code === 200) {
            this.active = 3
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
            });

          }
        })
      }
    },
    // 上一步的逻辑
    goBack() {
      if (this.active === 1) {
        this.active = 0
      } else if (this.active === 2) {
        this.active = 1
      }
    },
    // 忘记密码
    ForgotPassword() {
      this.active = 0
      this.innerVisible = true
    },

    // 打开对话框
    openDialog() {
      this.loginDialogVisible = true
    },
    // 关闭对话框
    closeDialog() {
      this.loginDialogVisible = false
    },
    innerVisibleCloseDialog() {
      this.innerVisible = false
      this.formLabelAlign = {}
    },
    // 登录
    login() {
      if (!this.form.username) {
        ElMessage({
          message: '请输入用户名',
          type: 'error',
        });
        return
      }
      if (!this.form.password) {
        ElMessage({
          message: '请输入密码',
          type: 'error',
        });
        return
      }
      let params = {
        loginName: this.form.username,
        password: this.form.password,
      }
      sysLogin(params).then((res) => {
        if (res.data.code == 200) {
          this.getSettingList()
          this.getPowerMenu()
          ElMessage({
            message: res.data.message,
            type: 'success',
          });
          this.compareData(res.data.data)
          this.closeDialog()
        } else {
          ElMessage({
            message: res.data.message,
            type: 'error',
          });

        }
      })
    },
    // 对比和缓存中的数据
    compareData(data) {
      localStorage.setItem('X-Access-Token', data.token)
      localStorage.setItem('userName', data.userInfo.realName)
      localStorage.setItem('loginName', data.userInfo.loginName)
      localStorage.setItem('createBy', data.userInfo.createBy)
      localStorage.setItem('accountId', data.userInfo.accountId)
      localStorage.setItem('theme', data.userInfo.theme ? data.userInfo.theme : '#409EFF')

      this.$store.commit('setUserId', data.userInfo.accountId)
      this.$store.commit('setTheme', data.userInfo.theme)
      document.documentElement.style.setProperty(
        '--menuItemHoverBackgroundColor',
        data.userInfo.theme
      )
      // 修改父组件的userName
      this.$parent.userName = data.userInfo.realName
      // 获取缓存的数据  获取的是上次登录的账号
      const createBy = localStorage.getItem('createBy')
      if (data.userInfo.createBy == createBy) {
        // 判断登录的账号是否与上次的账号一致 一致就删除面包屑
        localStorage.removeItem('visiteds')
      }
      this.closeDialog()
      this.$router.push({ path: '/' })
    },
    getSettingList() {
      settinglist().then((res) => {
        if (res.data.code == 200) {
          this.ruleForm = res.data.data[0]
          localStorage.setItem('cmPageNo', res.data.data[0].cmPageNo)
          this.$store.dispatch('getSettingFields', res.data.data[0])
        }
      })
    },
  },
  created() { },
  mounted() { },
}
</script>
<style lang="less" scoped>
:deep(.el-dialog) {
  background: rgb(58, 78, 115);

  .el-dialog__header {
    color: #f1f1f1;
    display: flex
  }
}

.el-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}

.formLabelAlign {
  .el-form-item__label {
    color: #f1f1f1;
  }
}

.checking {
  position: relative;
  height: 50px;

  .checkButton {
    position: absolute;
    left: 0;
  }

  .checkingButton {
    position: absolute;
    right: 0;
  }
}
</style>
